package com.james.codeauto.web;

import com.james.codeauto.tools.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * 调用的是接口
 */

public class HttpClient {


    /**
     * post请求以及参数是json
     *
     * @param url
     * @return
     */
    public static JSONObject doPostForJson(String url, JSONObject jsonObject, boolean isFormData) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().
                setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
                .setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
        httpPost.setConfig(requestConfig);
        List<NameValuePair> params=new ArrayList<>();
        if (isFormData) {
            Iterator<String> it = jsonObject.keys();


            while (it.hasNext()) {
// 获得key
                String key = it.next();
                String value = jsonObject.optString(key);
                System.out.println("key: " + key + ",value:" + value);

                params.add(new BasicNameValuePair(key,value));
            }
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        } else {
            httpPost.setHeader("Content-Type", "application/json");
        }
        httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36");

        try {
           if(!isFormData){
               httpPost.setEntity(new StringEntity(jsonObject.toString(), ContentType.create("application/json", "utf-8")));
               System.out.println("request parameters" + EntityUtils.toString(httpPost.getEntity()));
           }else{
               httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));

           }

            System.out.println("httpPost:" + httpPost);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(response.getEntity());
                System.out.println("result:" + result);
                jsonObject = new JSONObject(result);
                return jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return jsonObject;
        }
    }


    public static String doGetForJson(String url, JSONObject jsonObject) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        Iterator<String> it = jsonObject.keys();
        String bodyValTemplate = "";
        while (it.hasNext()) {
// 获得key
            String key = it.next();
            String value = jsonObject.optString(key);
            System.out.println("key: " + key + ",value:" + value);
            try {
                bodyValTemplate += "&" + key + "=" + URLEncoder.encode(value, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        HttpGet httpPost = new HttpGet(url + bodyValTemplate);
        RequestConfig requestConfig = RequestConfig.custom().
                setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
                .setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        String result = null;
        try {

            System.out.println("httpGet:" + httpPost);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                 result = EntityUtils.toString(response.getEntity());
                System.out.println("result:" + result);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }
}

